/**
 * 网络连接监控工具
 * 用于实时监控前端与后端的连接状态
 */

import { ref, reactive, onMounted, onUnmounted } from 'vue'
import request from './request'

// 网络状态
export const networkStatus = reactive({
  isOnline: navigator.onLine,
  connectionType: 'unknown',
  latency: 0,
  lastHealthCheck: null,
  healthCheckInterval: null,
  failedRequests: 0,
  totalRequests: 0,
  avgResponseTime: 0,
  statusHistory: []
})

// 监控配置
const MONITORING_CONFIG = {
  healthCheckInterval: 30000, // 30秒健康检查
  latencyCheckInterval: 10000,  // 10秒延迟检查
  maxHistoryEntries: 50,        // 最大历史记录数
  slowResponseThreshold: 5000,  // 慢响应阈值（5秒）
  connectionFailureThreshold: 3  // 连接失败阈值
}

// 健康检查函数
async function performHealthCheck() {
  try {
    const startTime = Date.now()

    const response = await request({
      url: '/health',
      method: 'GET',
      timeout: 5000 // 5秒超时
    })

    const latency = Date.now() - startTime
    networkStatus.latency = latency
    networkStatus.lastHealthCheck = new Date().toISOString()
    networkStatus.failedRequests = 0 // 重置失败计数

    // 记录状态历史
    addToHistory({
      timestamp: new Date().toISOString(),
      status: 'success',
      latency,
      message: '健康检查通过'
    })

    console.log('✅ 网络健康检查通过:', {
      latency: `${latency}ms`,
      timestamp: networkStatus.lastHealthCheck
    })

    return true
  } catch (error) {
    networkStatus.failedRequests++
    networkStatus.lastHealthCheck = new Date().toISOString()

    // 记录状态历史
    addToHistory({
      timestamp: new Date().toISOString(),
      status: 'error',
      error: error.message,
      failedCount: networkStatus.failedRequests
    })

    console.error('❌ 网络健康检查失败:', {
      error: error.message,
      failedCount: networkStatus.failedRequests,
      timestamp: networkStatus.lastHealthCheck
    })

    // 如果连续失败次数过多，触发警告
    if (networkStatus.failedRequests >= MONITORING_CONFIG.connectionFailureThreshold) {
      console.warn('⚠️ 网络连接不稳定，连续失败次数:', networkStatus.failedRequests)
      // 可以在这里添加用户通知逻辑
    }

    return false
  }
}

// 延迟测试函数
async function performLatencyTest() {
  try {
    const startTime = Date.now()

    await request({
      url: '/system/status',
      method: 'GET',
      timeout: 3000 // 3秒超时
    })

    const latency = Date.now() - startTime
    networkStatus.latency = latency

    console.log('📊 网络延迟测试:', `${latency}ms`)

    return latency
  } catch (error) {
    console.error('❌ 延迟测试失败:', error.message)
    return null
  }
}

// 添加到历史记录
function addToHistory(entry) {
  networkStatus.statusHistory.unshift(entry)

  // 限制历史记录数量
  if (networkStatus.statusHistory.length > MONITORING_CONFIG.maxHistoryEntries) {
    networkStatus.statusHistory = networkStatus.statusHistory.slice(0, MONITORING_CONFIG.maxHistoryEntries)
  }
}

// 计算平均响应时间
function calculateAvgResponseTime() {
  const recentEntries = networkStatus.statusHistory
    .filter(entry => entry.status === 'success' && entry.latency)
    .slice(0, 10) // 最近10次成功请求

  if (recentEntries.length === 0) return 0

  const totalLatency = recentEntries.reduce((sum, entry) => sum + entry.latency, 0)
  return Math.round(totalLatency / recentEntries.length)
}

// 获取连接类型
function getConnectionType() {
  const connection = (navigator as any).connection ||
                   (navigator as any).mozConnection ||
                   (navigator as any).webkitConnection

  if (!connection) return 'unknown'

  return connection.effectiveType || connection.type || 'unknown'
}

// 浏览器在线状态监听
function handleOnlineStatusChange() {
  networkStatus.isOnline = navigator.onLine

  if (navigator.onLine) {
    console.log('🌐 网络已连接')
    // 重新开始健康检查
    startHealthCheck()
  } else {
    console.warn('📵 网络已断开')
    // 停止健康检查
    stopHealthCheck()
  }
}

// 健康检查定时器
let healthCheckTimer = null
let latencyCheckTimer = null

// 开始健康检查 (已禁用)
function startHealthCheck() {
  console.log('🔍 网络监控已禁用')
  return
  
  /*
  stopHealthCheck() // 先停止现有的检查

  // 立即执行一次健康检查
  performHealthCheck()

  // 定期健康检查
  healthCheckTimer = setInterval(() => {
    performHealthCheck()
  }, MONITORING_CONFIG.healthCheckInterval)

  // 定期延迟测试
  latencyCheckTimer = setInterval(() => {
    performLatencyTest()
  }, MONITORING_CONFIG.latencyCheckInterval)

  networkStatus.healthCheckInterval = MONITORING_CONFIG.healthCheckInterval

  console.log('🔍 网络监控已启动:', {
    healthCheckInterval: `${MONITORING_CONFIG.healthCheckInterval / 1000}秒`,
    latencyCheckInterval: `${MONITORING_CONFIG.latencyCheckInterval / 1000}秒`
  })
  */
}

// 停止健康检查
function stopHealthCheck() {
  if (healthCheckTimer) {
    clearInterval(healthCheckTimer)
    healthCheckTimer = null
  }

  if (latencyCheckTimer) {
    clearInterval(latencyCheckTimer)
    latencyCheckTimer = null
  }

  networkStatus.healthCheckInterval = null
  console.log('⏹️ 网络监控已停止')
}

// 获取网络质量评级
function getNetworkQuality() {
  if (networkStatus.latency === 0) return 'unknown'

  if (networkStatus.latency < 100) return 'excellent'
  if (networkStatus.latency < 300) return 'good'
  if (networkStatus.latency < 1000) return 'fair'
  if (networkStatus.latency < 3000) return 'poor'
  return 'terrible'
}

// 获取连接状态描述
function getConnectionDescription() {
  if (!networkStatus.isOnline) return '离线'

  const quality = getNetworkQuality()
  const failedCount = networkStatus.failedRequests

  if (failedCount >= MONITORING_CONFIG.connectionFailureThreshold) {
    return `连接不稳定 (${failedCount}次失败)`
  }

  switch (quality) {
    case 'excellent': return '连接优秀'
    case 'good': return '连接良好'
    case 'fair': return '连接一般'
    case 'poor': return '连接较差'
    case 'terrible': return '连接很差'
    default: return '连接状态未知'
  }
}

// Vue组合式函数
export function useNetworkMonitor() {
  onMounted(() => {
    // 初始化连接类型
    networkStatus.connectionType = getConnectionType()

    // 添加事件监听器
    window.addEventListener('online', handleOnlineStatusChange)
    window.addEventListener('offline', handleOnlineStatusChange)

    // 开始健康检查
    startHealthCheck()
  })

  onUnmounted(() => {
    // 移除事件监听器
    window.removeEventListener('online', handleOnlineStatusChange)
    window.removeEventListener('offline', handleOnlineStatusChange)

    // 停止健康检查
    stopHealthCheck()
  })

  // 手动触发健康检查
  const checkHealth = () => performHealthCheck()

  // 手动触发延迟测试
  const checkLatency = () => performLatencyTest()

  return {
    networkStatus,
    checkHealth,
    checkLatency,
    getNetworkQuality,
    getConnectionDescription,
    isHealthy: () => networkStatus.isOnline && networkStatus.failedRequests < MONITORING_CONFIG.connectionFailureThreshold
  }
}

// 导出工具函数
export {
  startHealthCheck,
  stopHealthCheck,
  performHealthCheck,
  performLatencyTest,
  getNetworkQuality,
  getConnectionDescription
}

export default useNetworkMonitor